package com.lzxuni.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import net.sf.json.JSONObject;

public class UrlUtil {
    private CloseableHttpClient httpClient = HttpClients.createDefault();
    private CloseableHttpResponse response = null;
    private HttpEntity entity = null;
    private HttpEntity fileEntity = null;
    private Charset CHARSET = null;
    
    /**
     * 构造函数
     */
    public UrlUtil() {
        this.CHARSET = Consts.UTF_8;
    }
    /**
     * 设置文件编码
     * @param Charset
     */
    public void setCarest(Charset charset){
        this.CHARSET = charset;
    }
    /**
     * 获取文件编码
     * @return
     */
    public Charset getCarest(){
        return this.CHARSET;
    }
    /**
     * get方法
     * @param String url
     * @param Map<String,String> map
     * @return String
     */
    public String get(String uri,Map<String,String> map) {
        List<NameValuePair> list = (List<NameValuePair>) new ArrayList();
        Iterator<String> iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            String value = map.get(key);
            list.add(new BasicNameValuePair(key, value));
        }
        String param = URLEncodedUtils.format(list, this.CHARSET);
        String url = uri + "?" + param;
        HttpGet httpGet = new HttpGet(url);
        System.out.println(url);
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            
            entity = response.getEntity();
            if (entity != null) {
                result = EntityUtils.toString(entity,"UTF-8");
            }
        } catch (ClientProtocolException e) {
            result = e.getMessage();
        } catch (IOException e) {
        	e.printStackTrace();
            result = e.getMessage();
        }
        	try {
				response.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
        return result;
    }
    /**
     * 将返回实体放到缓冲区中
     * @author cuipengfei
     * @return String
     */
    public String getKeepEntity(String url){
        HttpGet httpGet = new HttpGet(url);
        String result = null;
        try {
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            entity = new BufferedHttpEntity(entity);
            response.close();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (ClientProtocolException e) {
            result = e.getMessage();
        } catch (IOException e) {
            result = e.getMessage();
        }
        return result;
    }
    /**
     * 模拟表单提交
     * @param uri表单提交的uri
     * @param Map<String, Object> 参数map
     * @return String
     */
    public String formPostData(String uri,Map<String, Object> map){
        HttpPost httpPost = new HttpPost(uri);
        String result = null;
        Map<String, File> fileMap = new HashMap();
        List<NameValuePair> formparams = new ArrayList();
        try {
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value =map.get(key);
                if (value instanceof File) {
                    fileMap.put(key, (File) value);
                    continue;
                }
                formparams.add(new BasicNameValuePair(key, (String)value));
            }
            UrlEncodedFormEntity setFormEntity = new UrlEncodedFormEntity(formparams,this.CHARSET);
            httpPost.setEntity(setFormEntity);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            result = e.getMessage();
        } catch (ClientProtocolException e) {
            result = e.getMessage();
        } catch (IOException e) {
            result = e.getMessage();
        }
        return result;
    }
    /**
     * 用于带文件的表单提交,也可用于普通表单提交，可多文件上传
     * @param uri 上传接口的uri
     * @param map
     * @return String
     */
    public String formPostFile(String uri,Map<String, Object> map){
        HttpPost httpPost = new HttpPost(uri);
        String result = null;
        MultipartEntityBuilder myEntityBuilder = MultipartEntityBuilder.create();
        try {
            Iterator<String> iterator = map.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                Object value =map.get(key);
                if (value instanceof File) {
                    myEntityBuilder.addPart(key, new FileBody((File) value));
                } else {
                    myEntityBuilder.addPart(key, new StringBody((String) value, ContentType.create("text/plain", this.CHARSET)));
                }
            }
            fileEntity = myEntityBuilder.build();
            httpPost.setEntity(fileEntity);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            result = EntityUtils.toString(entity,"UTF-8");
        } catch (UnsupportedEncodingException e) {
            result = e.getMessage();
        } catch (ClientProtocolException e) {
            result = e.getMessage();
        } catch (IOException e) {
            result = e.getMessage();
        }
        return result;
    }
    
    public static void main(String[] args){
    	
    	String result = null;
    	Map<String, String> map = new HashMap();
    	map.put("param", "参数");
    	String uri="http://apis.baidu.com/apistore/stockservice/stock";
    	UrlUtil httpClientUtil = new UrlUtil();
    	result = httpClientUtil.get(uri, map);
    	
    	//取Object
        JSONObject jsonObject = JSONObject.fromObject(result);
        Map<String, Object> hashmap = (Map<String, Object>) JSONObject.toBean(jsonObject, Map.class);
        System.out.println(hashmap);
        System.out.println("errNum:"+hashmap.get("errNum"));
        System.out.println("errMsg:"+hashmap.get("errNum"));
    }
}
